package com.hippo.core.vm

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson.JSONObject
import com.hippo.core.R
import com.hippo.core.core.ext.orZero
import com.hippo.core.respository.ApiRepository
import com.hippo.core.state.ConsumablesState
import com.hippo.core.tuya.DpInfo
import com.hippo.core.tuya.ThingControl
import com.hippo.core.tuya.ThingControl.devId
import com.hippo.core.ui.compose.control.ControlVM.Companion.TAG
import com.hippo.core.utils.UiHandler
import com.thingclips.smart.home.sdk.ThingHomeSdk
import com.thingclips.smart.sdk.api.IResultCallback
import com.thingclips.smart.sdk.api.IThingDevice
import kotlinx.coroutines.launch

class ConsumablesVM : ViewModel() {

    var uiState by mutableStateOf(ConsumablesState())

    private val thingDevice: IThingDevice = ThingHomeSdk.newDeviceInstance(devId)

    fun updateState(state: ConsumablesState) {
        uiState = state
    }

    init {
        getConsumablesInfo()

    }

    fun getConsumablesInfo() {

        viewModelScope.launch {

            val deviceId = ThingControl.devId.orEmpty()

            ApiRepository.getConsumablesInfo(deviceId)
                .handleFailure()
                .onSuccess {
                    uiState = uiState.copy(info = it)
                }

        }
    }



    fun publishDps(dpId:String,value: Any){

        val jsonObject = JSONObject()
        jsonObject[dpId] = value
        val dps = jsonObject.toString()

        Log.i(TAG, "publishDps: $dps")

        thingDevice.publishDps(dps,object : IResultCallback {
            override fun onError(code: String?, error: String?) {
                Log.d(TAG, "onError: code= $code  error= $error")
                UiHandler.showToast(error)
            }

            override fun onSuccess() {
                Log.d(TAG, "publishDps: onSuccess")
            }
        })
    }


    fun refreshSensor(){
        viewModelScope.launch {
            val deviceId = ThingControl.devId.orEmpty()
            ApiRepository.resetDeviceWarn(deviceId, 1)
                .handleFailure()
                .onSuccess {
                    UiHandler.showToast(R.string.success)
                }
        }
    }



    fun refreshBrush(){
        viewModelScope.launch {
            val deviceId = ThingControl.devId.orEmpty()
            ApiRepository.resetDeviceWarn(deviceId, 2)
                .handleFailure()
                .onSuccess {
                    UiHandler.showToast(R.string.success)
                }
        }
    }


}